import Vue from 'vue' //先导vue后导router
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import User from '../components/user/user.vue'
import Item from '../components/items/item.vue'
import AddItem from '../components/items/addItem.vue'
import ItemCat from '../components/items/itemCat.vue'
import ItemCatParam from '../components/items/itemCatParam.vue'

Vue.use(VueRouter)  //vue对象启用路由
const routes = [
  {path: '/', redirect: '/login'},
  {path: '/login', component: Login},
  {path: '/home',component: Home,
  redirect: '/welcome',
  children: [
    {path: '/welcome',component: Welcome},
    {path: '/user',component: User},
    {path: '/item',component: Item},
    {path: '/itemCat',component: ItemCat},
    {path: '/itemCatParam',component: ItemCatParam},
    {path: '/item/addItem',component: AddItem}
  ]}
]

const router = new VueRouter({
  routes    //和上方routes常量关联
})

router.beforeEach((to,from,next) => {
  //如果要去login，放行
  if(to.path === '/login') return next()
  //以下是其他请求判断
  //获取token信息
  let token = window.sessionStorage.getItem('token')
  //判断token是否为空
  //if(token)如果if的参数不是布尔值，那么有数据就是true，null就是false
  //next(xx) 跳转到xxx
  //如果为空，跳转至login
  if(!token) return next('/login')
  //不为空，放行
  next()

})

export default router
